from pydantic import model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from typing import Literal,Any
from functools import lru_cache
import os

class Settings(BaseSettings):

    model_config = SettingsConfigDict(
        env_file_encoding='utf-8',
        # 忽略未知的环境变量，防止错误,如果为allow,则允许未知变量保留在环境变量中
        extra='ignore',
    )

    # 环境变量，可以是 dev（开发环境）或 prod（生产环境）
    ENVIRONMENT: Literal['dev', 'prod']


    # FastAPI 的 API 路径、标题、版本、描述、文档路径和静态文件服务等配置
    FASTAPI_API_V1_PATH: str = '/v2'
    FASTAPI_TITLE: str = 'FastAPI'
    FASTAPI_VERSION: str = '0.0.1'
    FASTAPI_DESCRIPTION: str = 'SwiftForge Engine'
    FASTAPI_DOCS_URL: str | None = '/docs'
    FASTAPI_REDOCS_URL: str | None = '/redocs'
    FASTAPI_OPENAPI_URL: str | None = '/openapi'
    FASTAPI_STATIC_FILES: bool = True

    #系统标识
    SYSTEM_FLAG: str = 'sfe'

    # 数据库类型，可以是 mysql 或 doris
    DATABASE_TYPE: Literal['mysql', 'doris'] = 'mysql'

    # 数据库连接信息
    DATABASE_HOST: str = '127.0.0.1'
    DATABASE_PORT: int = 3306
    DATABASE_USER: str = 'root'
    DATABASE_PASSWORD: str = '123456a?'

    # 数据库的 schema 和字符集
    DATABASE_SCHEMA: str = 'sfe'
    DATABASE_CHARSET: str = 'utf8mb4'

    DATABASE_ECHO: bool = False  # 是否在终端打印数据库查询语句


    #DBGPT的api接口地址
    DBGPT_API_URL:str = 'http://localhost:5670/api/v2/chat/completions'

    #Vanna配置项
    VANNA_LOCAL_IP:str = '10.191.64.46'
    VANNA_BASE_URL:str = 'http://10.191.62.233:5997'
    VANNA_EMBEDDING_MODEL_UID:str = 'bge-m3'
    VANNA_LLM_MODEL_UID:str = 'deepseek-chat'

    # 日志的根级别
    LOG_ROOT_LEVEL: str = 'NOTSET'
    # 标准输出和文件输出的日志格式
    LOG_STD_FORMAT: str = (
        '<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</> | <lvl>{level: <8}</> | '
        '<cyan> {correlation_id} </> | <lvl>{message}</>'
    )
    LOG_FILE_FORMAT: str = (
        '<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</> | <lvl>{level: <8}</> | '
        '<cyan> {correlation_id} </> | <lvl>{message}</>'
    )
    # 日志中的 correlation ID 默认值和长度
    LOG_CID_DEFAULT_VALUE: str = '-'
    LOG_CID_UUID_LENGTH: int = 32  # must <= 32

    # 标准输出和标准错误的日志级别
    LOG_STDOUT_LEVEL: str = 'INFO'
    LOG_STDERR_LEVEL: str = 'ERROR'

    # 标准输出和标准错误的日志文件名
    LOG_STDOUT_FILENAME: str = f'{SYSTEM_FLAG}_access.log'
    LOG_STDERR_FILENAME: str = f'{SYSTEM_FLAG}_error.log'

    # 日期时间的时区和格式
    DATETIME_TIMEZONE: str = 'Asia/Shanghai'
    DATETIME_FORMAT: str = '%Y-%m-%d %H:%M:%S'

    """
        环境变量的检查
        如果为生产环境则关闭OpenAPI文档
    """
    @classmethod
    @model_validator(mode='before')
    def check_env(cls,values:Any) -> Any:
        if values.get('ENVIRONMENT') == 'prod':
            values['FASTAPI_DOCS_URL'] = None
            values['FASTAPI_REDOCS_URL'] = None
            values['FASTAPI_OPENAPI_URL'] = None
        return values

@lru_cache
def get_settings() -> Settings:
    #获取全局配置
    environment = os.getenv('APP_ENV', 'dev')
    #动态生成配置文件路径
    env_file = f'.env.{environment}'
    return Settings(_env_file=env_file)

#创建配置实例
settings = get_settings()
